<?php
class Cms_DbTable extends Zend_Db_Table {
	
	protected static $_adapters = false;
	
	public $__adapter = 'default';
	
	public function __construct() {
		if (isset ( $this->__adapter ) && $this->__adapter != 'default' && self::$_adapters) {
			if (self::$_adapters [$this->__adapter]) {
				$___adapters = self::$_adapters [$this->__adapter];
				parent::__construct ( $___adapters );
			}
			$this->_name = self::$_adapters [$this->__adapter]->_config ['prefix'] . $this->_name;
		} else {
			$_da = $this->getDefaultAdapter ();
			$_da_conf = $_da->getConfig ();
			$this->_name = $_da_conf ['prefix'] . $this->_name;
			parent::__construct ();
		}
	}
	
	/**
	 * 设置多个数据库
	 *
	 * @param $adapter_conf_arr array       	
	 */
	static function setAdapters($adapter_conf_arr) {
		if (! self::$_adapters) {
			self::$_adapters = $adapter_conf_arr;
		}
	}
	
	public function setAdapter($app) {
		$this->__adapter = $app;
	}
	
	public function getAdapters() {
		return self::$_adapters;
	}
	
	/**
	 * 取得list信息
	 *
	 * @param $field mix       	
	 * @param $where,eg:"fildname=1" mix
	 *       	 or array('fildname=?'=>1)
	 * @param $order,eg:"fildname string
	 *       	 DESC" or "fildname ASC"
	 * @param $limit mix       	
	 * @param $group string       	
	 */
	public function loadList($fields = null, $where = null, $order = null, $limit = null, $group = null) {
		$select = $this->select ();
		// 字段
		if ($fields) {
			if (is_string ( $fields )) {
				$_fields_arr = explode ( ',', $fields );
				foreach ( $_fields_arr as $_fields_key => $_fields_info ) {
					$_fields_arr [$_fields_key] = trim ( $_fields_info );
				}
			} elseif (is_array ( $fields )) {
				$_fields_arr = $fields;
			}
			$select->from ( $this->_name, $_fields_arr );
		} else {
			$select->from ( $this->_name, '*' );
		}
		
		// 条件
		if ($where) {
			if (is_array ( $where )) {
				foreach ( $where as $key => $value ) {
					$select->where ( $key, $value );
				}
			} else {
				$select->where ( $where );
			}
		}
		if ($limit) {
			if (is_string ( $limit )) {
				$limit = explode ( ',', $limit );
			}
			if (is_array ( $limit ) && count ( $limit ) == 2) {
				$select->limit ( $limit [0], $limit [1] );
			} elseif (is_numeric ( $limit )) {
				$select->limit ( $limit );
			}
		}
		if ($order) {
			if (is_array ( $order )) {
				$_orders_arr = $order;
			} else {
				$_orders_arr = explode ( ',', $order );
				foreach ( $_orders_arr as $_orders_key => $_order_info ) {
					$_orders_arr [$_orders_key] = trim ( $_order_info );
				}
			
			}
			$select->order ( $_orders_arr );
		}
		if ($group) {
			if (is_array ( $group )) {
				$_groups_arr = $group;
			} else {
				$_groups_arr = explode ( ',', $group );
				foreach ( $_groups_arr as $_orders_key => $_order_info ) {
					$_groups_arr [$_orders_key] = trim ( $_order_info );
				}
			
			}
			$select->group ( $_groups_arr );
		}
		
		try {
			$result = $this->fetchAll ( $select );
		} catch ( Exception $e ) {
			throw new Zend_Db_Table_Select_Exception ( 'Select query error:<br /><br />' . $select->__toString () . '<br /><br />' . $e->getMessage () );
		}
		return $result ? $result->toArray () : null;
	}
	
	/**
	 * 取得一条信息
	 *
	 * @param $field string       	
	 * @param $where string       	
	 * @param $order string       	
	 * @param $group string       	
	 */
	public function loadInfo($fields = null, $where = null, $order = null, $limit = null, $group = null) {
		$select = $this->select ();
		// 字段
		if ($fields) {
			if (is_string ( $fields )) {
				$_fields_arr = explode ( ',', $fields );
			} elseif (is_array ( $fields )) {
				$_fields_arr = $fields;
			}
			$select->from ( $this->_name, $_fields_arr );
		} else {
			$select->from ( $this->_name, '*' );
		}
		
		if ($where && is_array ( $where )) {
			foreach ( $where as $key => $value ) {
				$select->where ( $key, $value );
			}
		} else {
			$where ? $select->where ( $where ) : null;
		}
		$order ? $select->order ( $order ) : null;
		$limit ? $select->limit ( $limit ) : null;
		$group ? $select->group ( $group ) : null;
		
		try {
			$result = $this->fetchRow ( $select );
		} catch ( Exception $e ) {
			throw new Zend_Db_Table_Select_Exception ( 'Select query error:<br /><br />' . $select->__toString () . '<br /><br />' . $e->getMessage () );
		}
		return $result ? $result->toArray () : null;
	}
	
	/**
	 * 根据主键查找数据
	 *
	 * @param $prm_key int
	 *       	 主键
	 * @return one row info
	 */
	public function loadInfoByPrimary($prm_key) {
		$select = $this->select ();
		$select->where ( $this->getPrimary () . "=?", $prm_key );
		try {
			$result = $this->fetchRow ( $select );
		} catch ( Exception $e ) {
			throw new Zend_Db_Table_Select_Exception ( 'Select query error:<br /><br />' . $select->__toString () . '<br /><br />' . $e->getMessage () );
		}
		return $result ? $result->toArray () : null;
	}
	
	/**
	 * 更新信息
	 *
	 * @param $set_arr array
	 *       	 数组格式 更新的列
	 * @param $where mix
	 *       	 数组格式 array("quiz_title=?"=>"111") = ("quiz_title=?","111")
	 */
	public function updateByConditions($set_arr, $where) {
		$db = $this->getAdapter ();
		$where_sql = "1=1";
		if ($where && is_array ( $where )) {
			foreach ( $where as $key => $value ) {
				$where_sql .= $db->quoteInto ( " AND $key", $value );
			}
		} else {
			// $where_sql.= $db->quoteInto("$where");
			$where_sql = $where;
		}
		
		try {
			$rows_affected = $this->update ( $set_arr, $where_sql );
		} catch ( Exception $e ) {
			foreach ( $set_arr as $col => $val ) {
				$set [] = $this->_db->quoteIdentifier ( $col, true ) . ' = ' . $val;
			}
			throw new Zend_Db_Table_Select_Exception ( 'Update query error:<br /><br />' . "UPDATE " . $this->_name . ' SET ' . implode ( ', ', $set ) . (($where_sql) ? " WHERE $where_sql" : '') . '<br /><br />' . $e->getMessage () );
		}
		return $rows_affected;
	}
	
	public function updateByPrimary($set_arr, $prm_key) {
		return $this->updateByConditions ( $set_arr, array ($this->getPrimary () . '=?' => $prm_key ) );
	}
	
	/**
	 * 取得总数
	 *
	 * @param $count_field string       	
	 * @param $where mix       	
	 * @param $fields string       	
	 * @param $group mix       	
	 * @return int
	 */
	public function loadCount($count_field = null, $where = null, $fields = null, $group = null) {
		$count_field ? $cfield = 'count(' . trim ( $count_field ) . ')' : $cfield = 'count(*)';
		if ($fields && is_string ( $fields )) {
			$field = $cfield . "," . $fields;
		} else {
			$field = $cfield;
		}
		
		if ($group) {
			return $this->loadList ( $field, $where, null, null, $group );
		} else {
			$_result = $this->loadInfo ( $field, $where, null, null, $group );
			if (! $_result [$field]) {
				$_result [$field] = 0;
			}
			return $_result [$field];
		}
	}
	
	/**
	 * 对某一列加1
	 *
	 * @param $field string       	
	 * @param $where mix       	
	 * @return boolean
	 */
	public function incrField($field, $where) {
		return $this->updateByConditions ( array ($field => new Zend_Db_Expr ( $field . '+1' ) ), $where );
	}
	/**
	 * 对某一列加1
	 *
	 * @param $field string       	
	 * @param $where mix       	
	 * @return Boolean
	 */
	public function DecrField($field, $where) {
		return $this->updateByConditions ( array ($field => new Zend_Db_Expr ( $field . '-1' ) ), $where );
	}
	
	/**
	 * 对某一列加值
	 *
	 * @param $field string       	
	 * @param $where mix       	
	 * @return Boolean
	 */
	public function incrFieldValue($field, $add_value, $where) {
		return $this->updateByConditions ( array ($field => new Zend_Db_Expr ( $field . '+' . $add_value ) ), $where );
	}
	
	/**
	 * 对某一列加值
	 *
	 * @param $field string       	
	 * @param $where mix       	
	 * @return Boolean
	 */
	public function DecrFieldValue($field, $add_value, $where) {
		return $this->updateByConditions ( array ($field => new Zend_Db_Expr ( $field . '-' . $add_value ) ), $where );
	}
	
	/**
	 * 执行Sql语句
	 *
	 * @param $sql string       	
	 * @param
	 *       	 int or array $limit
	 * @param $bind array       	
	 * @return array
	 */
	public function findBySql($sql, $limit = null, $bind = array()) {
		if ($limit) {
			if (is_numeric ( $limit )) {
				$sql .= " LIMIT " . $limit;
			} elseif (is_array ( $limit )) {
				$sql .= " LIMIT " . $limit [1] . "," . $limit [0];
			}
		}
		try {
			$stmt = $this->_db->prepare ( $sql );
			$result = $stmt->execute ();
		} catch ( Exception $e ) {
			throw new Zend_Db_Table_Select_Exception ( 'Sql query error:<br /><br />' . $sql . '<br /><br />' . $e->getMessage () );
		}
		
		if (strtolower ( substr ( trim ( $sql ), 0, 6 ) ) == "select") {
			$result = $stmt->fetchAll ();
		}
		return $result;
	}
	
	/**
	 * 输出DB信息
	 */
	public function __debug() {
		$profiler = $this->_db->getProfiler ();
		return $profiler->getQueryProfiles ();
	}
	
	/**
	 * 最后一次的数据库请求语句
	 *
	 * @return string
	 */
	public function getLastQueryInfo() {
		$profiler = $this->_db->getProfiler ();
		return $profiler->getLastQueryProfile ();
	}
	
	/**
	 * 获取表名
	 *
	 * @return string
	 */
	public function getTableName() {
		return $this->_name;
	}
	
	/**
	 * 得到主键
	 *
	 * @return string
	 */
	public function getPrimary() {
		if (is_array ( $this->_primary ) && $this->_primary [1]) {
			return $this->_primary [1];
		} else {
			return $this->_primary;
		}
	}
}
?>